package com.fwtai;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.http.HttpServer;
import io.vertx.core.http.HttpServerOptions;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpVersion;
import io.vertx.core.json.Json;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;

import java.util.Arrays;
import java.util.List;

/*
 * @作者 田应平
 * @版本 v1.0
 * @创建时间 2021-06-30 15:22
 * @QQ号码 444141300
 * @Email service@dwlai.com
 * @官网 http://www.fwtai.com
 */
public final class Upload extends AbstractVerticle{

  private final InternalLogger logger = Log4JLoggerFactory.getInstance(getClass());

  private final String uploadDir = "C:\\upload";

  @Override
  public void start(final Promise<Void> startPromise) throws Exception {
    final List<HttpVersion> alpns = Arrays.asList(HttpVersion.HTTP_1_1,HttpVersion.HTTP_2);
    final HttpServerOptions serverOptions = new HttpServerOptions();
    serverOptions.setAlpnVersions(alpns);

    final HttpServer server = vertx.createHttpServer(serverOptions);

    final Router router = Router.router(vertx);

    router.route().handler(this::AuthInterceptor);//拦截器|过滤器

    // http://127.0.0.1:7008
    router.get("/").handler(context->{
      final JsonObject jsonObject = new JsonObject();
      jsonObject.put("code",200);
      jsonObject.put("msg","操作成功");
      response(context,jsonObject.encode());
    });

    server.requestHandler(req->{
      req.setExpectMultipart(true);
      req.exceptionHandler(err->{
        err.printStackTrace();
        final JsonObject jsonObject = new JsonObject();
        jsonObject.put("code",204);
        jsonObject.put("msg",err.getMessage());
        response(req,jsonObject);
        return;
      });
      final HttpMethod method = req.method();
      final String reqPath = req.path();
      System.out.println("method: " + method + " , reqPath: " + reqPath);
      if(reqPath.equals("/api/upload")){
        final String name = req.getParam("name"); // 默认 yyyy/MM/dd 文件夹位置 name=xxxx.jpg
        final String path = req.getParam("path");
        req.uploadHandler(upload->{
          final String fileName = upload.filename();
          upload.streamToFileSystem(uploadDir+"\\"+fileName).map(fileUpload -> {
            return uploadDir+"\\"+fileName;
          });
        });
      }else{
        final JsonObject jsonObject = new JsonObject();
        jsonObject.put("code",404);
        jsonObject.put("msg","访问的路径不存在");
        response(req,jsonObject);
      }
    });

    router.errorHandler(500,context->{
      final JsonObject jsonObject = new JsonObject();
      jsonObject.put("code",204);
      jsonObject.put("msg",context.failure().getMessage());
      response(context,jsonObject.encode());
    });

    final int port = 7008;
    server.requestHandler(router).listen(port,http -> {
      if (http.succeeded()){
        startPromise.complete();//todo 告知vert启动完毕
        logger.info("---应用启动成功---,http://127.0.0.1:"+port);
      } else {
        logger.error("Launcher应用启动失败,"+http.cause());
      }
    });
  }



  private void AuthInterceptor(final RoutingContext context){
    logger.info("请求:"+context.request().path());//todo 记得处理静态资源,图片,登录接口
    //ToolClient.responseJson(context,ToolClient.jsonPermission());//终止返回
    context.next();//继续下一个操作
  }

  public static void response(final RoutingContext context,final String json){
    context.response().putHeader("Cache-Control","no-cache").putHeader("content-type","text/html;charset=utf-8").end(json);
  }

  private static void response(final HttpServerRequest request,final JsonObject ret){
    request.response().putHeader("content-type","text/html;charset=utf-8").putHeader("Access-Control-Allow-Origin","*").putHeader("Access-Control-Allow-Credentials","true").putHeader("Content-Disposition","attachment").end(Json.encodePrettily(ret));
  }
}